import React, { Component } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Select, Input, Card, Table, Row, Col, Button, Icon, Form, Tooltip } from 'antd';
import styles from './index.less';
import Mpagination from '../components/Mpagination';
import * as apis from '@/services/SystemMgr';

const { Option } = Select;
@Form.create()
export default class SystemLog extends Component {
  state = {
    expand: true,
    total: '0', // 列表的总条数
    current: '1', // 当前页数
    pageSize: '20', // 每页条数
    pages: '0', // 总页数
    event: '',
    source: '',
    type: '',
    title: '',
    content: '',
    columns: [
      {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
        width: 30,
        align: 'center',
      },
      {
        title: '用户名',
        dataIndex: 'useraccount',
        key: 'useraccount',
        width: 60,
        render: text => (
          <Tooltip placement="topLeft" title={text}>
            <div
              style={{
                width: '100%',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
              }}
            >
              {text}
            </div>
          </Tooltip>
        ),
      },
      {
        title: '标题',
        dataIndex: 'title',
        key: 'title',
        width: 80,
        render: text => (
          <Tooltip placement="topLeft" title={text}>
            <div
              style={{
                width: '100%',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
              }}
            >
              {text}
            </div>
          </Tooltip>
        ),
      },
      {
        title: '模块',
        dataIndex: 'module',
        key: 'module',
        width: 70,
        render: text => (
          <Tooltip placement="topLeft" title={text}>
            <div
              style={{
                width: '100%',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
              }}
            >
              {text}
            </div>
          </Tooltip>
        ),
      },
      {
        title: '日志类型',
        dataIndex: 'type',
        key: 'type',
        width: 70,
        render: text => (text * 1 === 0 ? '操作日志' : '系统日志'),
      },
      {
        title: 'IP地址',
        dataIndex: 'ip',
        key: 'ip',
        width: 70,
        render: text => (
          <Tooltip placement="topLeft" title={text}>
            <div
              style={{
                width: '100%',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
              }}
            >
              {text}
            </div>
          </Tooltip>
        ),
      },
      {
        title: 'URL',
        dataIndex: 'url',
        key: 'url',
        width: 200,
        render: text => (
          <Tooltip placement="topLeft" title={text}>
            <div
              style={{
                width: '100%',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
              }}
            >
              {text}
            </div>
          </Tooltip>
        ),
      },
      {
        title: '事件',
        dataIndex: 'event',
        key: 'event',
        width: 60,
      },
      {
        title: '日志内容',
        dataIndex: 'content',
        key: 'content',
        width: 80,
        render: text => (
          <div>
            <Tooltip
              placement="topLeft"
              title={<div style={{ maxHeight: '140px', overflow: 'auto' }}>{text}</div>}
            >
              <div
                style={{
                  width: '100%',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                }}
              >
                {text}
              </div>
            </Tooltip>
          </div>
        ),
      },
      {
        title: '访问来源',
        dataIndex: 'source',
        key: 'source',
        width: 60,
      },
      {
        title: '创建时间',
        dataIndex: 'createStr',
        key: 'createStr',
        width: 100,
        render: text => (
          <Tooltip placement="topLeft" title={text}>
            <div
              style={{
                width: '100%',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
              }}
            >
              {text}
            </div>
          </Tooltip>
        ),
      },
    ],
    data: [],
    sourceData: [],
    eventsData: [],
    logtypeData: [],
  };

  componentDidMount() {
    const { current, pageSize, event, source, title, content } = this.state;
    this.requestTableData({ current, pageSize, event, source, title, content });
    apis
      .getDictionaryByTypeCodeUsingGET({
        params: {
          typeCode: 'access_source',
        },
      })
      .then(data => {
        if (data.code && data.code === 1) {
          this.setState({ sourceData: data.data });
        }
      });
    apis
      .getDictionaryByTypeCodeUsingGET({
        params: {
          typeCode: 'opt_events',
        },
      })
      .then(data => {
        if (data.code && data.code === 1) {
          this.setState({ eventsData: data.data });
        }
      });
    apis
      .getDictionaryByTypeCodeUsingGET({
        params: {
          typeCode: 'log_type',
        },
      })
      .then(data => {
        if (data.code && data.code === 1) {
          this.setState({ logtypeData: data.data });
        }
      });
  }

  // 分页切换
  handlePaginationChange = (current, pageSize) => {
    const { event, source, title, type, content } = this.state;
    this.requestTableData({ current, pageSize, event, source, title, type, content });
  };

  // 点击高级筛选按钮
  handleScreenBtn = () => {
    const { expand } = this.state;
    this.setState({
      expand: !expand,
    });
  };

  // 查询
  handleSearchBtn = e => {
    e.preventDefault();
    const { form } = this.props;
    const values = form.getFieldsValue();
    this.setState(values);
    const params = { ...values, pageSize: this.state.pageSize, current: '1' };
    this.requestTableData(params);
  };

  // 请求表格数据
  requestTableData(params) {
    this.setState({ data: [], loading: true });
    apis
      .getLogPageUsingGET({
        params,
      })
      .then(data => {
        if (data.code && data.code === 1) {
          const { list } = data.data;
          list.forEach((item, index) => {
            const x = item;
            x.key = item.id;
            x.index = data.data.pageSize * (data.data.current - 1) + index + 1;
          });
          this.setState({
            data: list,
            current: data.data.current,
            pageSize: data.data.pageSize,
            pages: data.data.pages,
            total: data.data.total,
            loading: false,
          });
        }
      });
  }

  render() {
    const { columns, data, expand, sourceData, eventsData, logtypeData, loading } = this.state;
    const { getFieldDecorator } = this.props.form;
    const tableHeight = document.body.clientHeight - (expand ? 200 : 332);
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 15 },
      style: { marginBottom: 0 },
    };
    return (
      <div className={styles.SystemLog}>
        <PageHeaderWrapper
          breadcrumb={null}
          extra={
            <Button onClick={this.handleScreenBtn}>
              高级筛选
              <Icon type={expand ? 'down' : 'up'} />
            </Button>
          }
        >
          <Form
            onSubmit={this.handleSearchBtn}
            layout="horizontal"
            style={{ display: expand ? 'none' : 'block' }}
          >
            <Row type="flex" justify="space-around" align="middle">
              <Col md={21} sm={24}>
                <Row>
                  <Col md={8} sm={24}>
                    <Form.Item {...formItemLayout} label="标题">
                      {getFieldDecorator('title')(<Input placeholder="请输入标题" />)}
                    </Form.Item>
                  </Col>
                  <Col md={8} sm={24}>
                    <Form.Item {...formItemLayout} label="内容">
                      {getFieldDecorator('content')(<Input placeholder="日志内容" />)}
                    </Form.Item>
                  </Col>
                  <Col md={8} sm={24}>
                    <Form.Item {...formItemLayout} label="访问来源">
                      {getFieldDecorator('source')(
                        <Select placeholder="请选择">
                          {sourceData.map(item => (
                            <Option value={item.dict_value} key={item.dict_value}>
                              {item.dict_name === '请选择' ? '全部' : item.dict_name}
                            </Option>
                          ))}
                        </Select>,
                      )}
                    </Form.Item>
                  </Col>
                  <Col md={8} sm={24}>
                    <Form.Item {...formItemLayout} label="操作事件">
                      {getFieldDecorator('event')(
                        <Select placeholder="请选择">
                          {eventsData.map(item => (
                            <Option value={item.dict_value} key={item.dict_value}>
                              {item.dict_name === '请选择' ? '全部' : item.dict_name}
                            </Option>
                          ))}
                        </Select>,
                      )}
                    </Form.Item>
                  </Col>
                  <Col md={8} sm={24}>
                    <Form.Item {...formItemLayout} label="日志类型">
                      {getFieldDecorator('type')(
                        <Select placeholder="请选择">
                          {logtypeData.map(item => (
                            <Option value={item.dict_value} key={item.dict_value}>
                              {item.dict_name === '请选择' ? '全部' : item.dict_name}
                            </Option>
                          ))}
                        </Select>,
                      )}
                    </Form.Item>
                  </Col>
                </Row>
              </Col>
              <Col md={3} sm={24} justify="space-around" align="middle">
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={() => this.props.form.resetFields()}>
                  重置
                </Button>
              </Col>
            </Row>
          </Form>
          <Card className="content">
            <Table
              loading={loading}
              bordered
              size="middle"
              scroll={{ y: tableHeight }}
              pagination={false}
              columns={columns}
              dataSource={data}
            />
            <Mpagination
              total={this.state.total}
              pageSize={this.state.pageSize}
              current={this.state.current}
              pages={this.state.pages}
              handlePaginationChange={this.handlePaginationChange}
              onShowSizeChange={(current, pageSize) =>
                this.handlePaginationChange(current, pageSize)
              }
            />
          </Card>
        </PageHeaderWrapper>
      </div>
    );
  }
}
